﻿using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraGrid.Columns;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Net.Mime;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;

namespace EmailSendSystem
{
    [ComVisible(true)]
    public partial class frmEmailSendto : Form
    {
        #region 参数
        private string _content = "";//txt变量
        #endregion

        #region 构造函数
        public frmEmailSendto()
        {
            InitializeComponent();
        }

        private void frmEmailSendto_Load(object sender, EventArgs e)
        {
            Init();
        }
        #endregion

        #region 初始化
        private void Init()
        {
            //初始化读取模版
            this.txtnotice.Url = new System.Uri(Application.StartupPath + "\\Plugins\\kindeditor\\e.html", System.UriKind.Absolute);
            this.txtnotice.ObjectForScripting = this;//加载js,必须给当前类加ComVisible 属性,确保对com可见

            InitData();
        }

        private void InitData()
        {
            SetGridLookUpEditMoreColumnFilter(txtaddresser.Properties);
            List<Addresser> Addressers = new List<Addresser>();
            Addressers.Add(new Addresser()
            {
                name = "xxx",
                caccount = "xxx",
                password = "xxx"
            });
            txtaddresser.Properties.DataSource = Addressers;
            txtaddresser.Properties.ValueMember = "name";
            txtaddresser.Properties.DisplayMember = "name";

            List<Addresser> recipients = new List<Addresser>();
            recipients.Add(new Addresser()
            {
                name = "xxx",
                caccount = "xxx@qq.com",
                password = ""
            });
            recipients.Add(new Addresser()
            {
                name = "xxx",
                caccount = "xxx@qq.com",
                password = ""
            });
            txtrecipients.Properties.DataSource = recipients;
            txtrecipients.Properties.ValueMember = "caccount";
            txtrecipients.Properties.DisplayMember = "caccount";
        }

        private Addresser GetSelectRow
        {
            get { return txtaddresser.GetSelectedDataRow() as Addresser; }
        }

        #region  web的HTML
        //操作txt源码框时的方法
        public void SetDetailContent()
        {
            txtnotice.Document.InvokeScript("setContent", new object[] { _content });
        }
        //内容初始值,否则webbrowser刚开始会没值
        public string GetContent()
        {
            return _content;
        }
        //如果在窗体load事件为其赋值则用于窗体加载完,为webBrowser重新赋值
        public void RequestContent(string str)
        {
            _content = str;
        }
        //操作webbrowser页面,刷新本身
        private void txtnotice_Resize(object sender, EventArgs e)
        {
            this.txtnotice.Refresh();
        }
        #endregion
        #endregion

        #region 窗体操作
        private void GetFrom(EmailSend model)
        {
            SetDetailContent();
            model.addresser = GetSelectRow;
            model.recipients = HandelStr(txtrecipients.Text.Trim()); ;
            model.titlite = txttitlite.Text.Trim();
            model.context = _content;
            model.accessoryPath = txtaccessory.Lines.ToList();
        }

        private void SetFrom(EmailSend model)
        {
            txtaddresser.Text = model.addresser.name;
            //txtrecipients.Text = model.recipients;
            txttitlite.Text = model.titlite;
            _content = model.context;
            SetDetailContent();
        }

        private void ClearFrom()
        {
            //txtaddresser.Text = "";
            //txtrecipients.Text = "";
            txttitlite.Text = "";
            _content = "";
            SetDetailContent();
            txtaccessory.Text = "";
        }

        #endregion

        #region 方法
        /// <summary>
        /// 设置GridLookUpEdit多列过滤
        /// </summary>
        /// <param name="repGLUEdit">GridLookUpEdit的知识库，eg:gridlookUpEdit.Properties</param>
        public void SetGridLookUpEditMoreColumnFilter(RepositoryItemGridLookUpEdit repGLUEdit)
        {
            repGLUEdit.EditValueChanging += (sender, e) =>
            {
                BeginInvoke(new System.Windows.Forms.MethodInvoker(() =>
                {
                    GridLookUpEdit edit = sender as GridLookUpEdit;
                    DevExpress.XtraGrid.Views.Grid.GridView view = edit.Properties.View as DevExpress.XtraGrid.Views.Grid.GridView;
                    //获取GriView私有变量
                    System.Reflection.FieldInfo extraFilter = view.GetType().GetField("extraFilter", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    List<DevExpress.Data.Filtering.CriteriaOperator> columnsOperators = new List<DevExpress.Data.Filtering.CriteriaOperator>();
                    foreach (GridColumn col in view.VisibleColumns)
                    {
                        if (col.Visible && col.ColumnType == typeof(string))
                            columnsOperators.Add(new DevExpress.Data.Filtering.FunctionOperator(DevExpress.Data.Filtering.FunctionOperatorType.Contains,
                                new DevExpress.Data.Filtering.OperandProperty(col.FieldName),
                                new DevExpress.Data.Filtering.OperandValue(edit.Text)));
                    }
                    string filterCondition = new DevExpress.Data.Filtering.GroupOperator(DevExpress.Data.Filtering.GroupOperatorType.Or, columnsOperators).ToString();
                    extraFilter.SetValue(view, filterCondition);
                    //获取GriView中处理列过滤的私有方法
                    System.Reflection.MethodInfo ApplyColumnsFilterEx = view.GetType().GetMethod("ApplyColumnsFilterEx", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
                    ApplyColumnsFilterEx.Invoke(view, null);
                }));
            };
        }

        private List<string> HandelStr(string txt)
        {
            txt = txt.Replace(" ", "");
            return txt.Split(',').ToList();
        }
        /// <summary>
        /// 发送邮件
        /// </summary>
        /// <param name="model"></param>
        private void Send163Email(EmailSend model)
        {
            MailMessage mailMsg = new MailMessage();
            //发件人
            mailMsg.From = new MailAddress(model.addresser.caccount);
            //收件人
            foreach (var it in model.recipients)
            {
                mailMsg.To.Add(new MailAddress(it));
            }
            //标题
            mailMsg.Subject = model.titlite;
            //正文
            mailMsg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(model.context, Encoding.UTF8, MediaTypeNames.Text.Html));
            //附件
            if (model.accessoryPath != null)
                foreach (string path in model.accessoryPath)
                {
                    mailMsg.Attachments.Add(new Attachment(path));
                }

            SmtpClient smtpClient = new SmtpClient("smtp.126.com", 25);
            System.Net.NetworkCredential credentials = new System.Net.NetworkCredential(model.addresser.name, model.addresser.password);
            smtpClient.Credentials = credentials;
            smtpClient.Send(mailMsg);
            smtpClient.Dispose();
        }
        /// <summary>
        /// 选择附件的路径
        /// </summary>
        /// <returns></returns>
        private List<string> GetPaths()
        {
            List<string> paths = new List<string>();
            using (OpenFileDialog ofdlg = new OpenFileDialog())
            {
                ofdlg.Filter = "*|*";
                ofdlg.Multiselect = true;
                ofdlg.Title = "最多选择5个文件";
                if (ofdlg.ShowDialog().Equals(DialogResult.OK))
                    paths = ofdlg.FileNames.ToList();
            }
            return paths;
        }
        #endregion

        #region 事件
        private void btnSendEmail_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtaddresser.Text)) return;
            if (string.IsNullOrWhiteSpace(txtrecipients.Text)) return;
            EmailSend model = new EmailSend();
            GetFrom(model);
            Send163Email(model);
            ClearFrom();
        }

        private void lytxtaccessory_Click(object sender, EventArgs e)
        {
            List<string> paths = GetPaths();
            if (paths != null && paths.Count() > 0)
            {
                txtaccessory.Text = string.Join("\r\n", paths);
            }
        }
        #endregion
    }
    #region 邮件类
    /// <summary>
    /// 邮件发送类
    /// </summary>
    public class EmailSend
    {
        /// <summary>
        /// 发件人
        /// </summary>
        public Addresser addresser { get; set; }
        /// <summary>
        /// 收件人
        /// </summary>
        public List<string> recipients { get; set; }
        /// <summary>
        /// 标题
        /// </summary>
        public string titlite { get; set; }
        /// <summary>
        /// 内容
        /// </summary>
        public string context { get; set; }
        /// <summary>
        /// 附件地址
        /// </summary>
        public List<string> accessoryPath { get; set; }
    }

    /// <summary>
    /// 发件人
    /// </summary>
    public class Addresser
    {
        /// <summary>
        /// 账号名称
        /// </summary>
        public string name { get; set; }
        /// <summary>
        /// 账号
        /// </summary>
        public string caccount { get; set; }
        /// <summary>
        /// 秘钥
        /// </summary>
        public string password { get; set; }
    }
    #endregion
}
